<?php
use \Entities\User;

class IndexController extends Front_Libraries_Controller_Action
{
    
    public function indexAction()
    {
        $this->view->friends = array(array('name'=>'duc.do'),array('name'=>'duy.nguyen'));
        $this->view->userInfo = $this->userInfo;
    }
    
    public function editprofileAction()
    {
        $ediForm = new Front_Form_Editprofile();
        $messages = array();
        $request = $this->_request;
        if($request->isPost())  
        {
            $ediForm->populate(array(
                'id' => $request->getParam('id'),
                'username' => $request->getParam('username'),
                'name' => $request->getParam('name'),
                'mobile' => $request->getParam('mobile'),
                'email' => $request->getParam('email'),
                'department' => $request->getParam('department'),
            ));
            
            if($this->userInfo->getId()==$ediForm->getValue('id')) 
            {
                if($ediForm->isValid($request->getPost()))  
                {
                    // get the username and password from the form  
                    $contact = $this->_em->getRepository('Entities\User')->find($this->userInfo->getId());
                    $contact->setName($request->getParam('name'));
                    $contact->setMobilephone($request->getParam('mobile'));
                    $contact->setEmail($request->getParam('email'));

                    $department = $this->_em->getRepository('Entities\Department')->find($request->getParam('department'));
                    $contact->setDepartment($department);

                    $password = $request->getParam('new_password');
                    if(!empty($password)) {
                        $contact->encryptPassword($request->getParam('new_password'));
                    }
                    $this->_em->flush();
                    $messages['success'] = "Your contact has been saved";
                } else {
                    $messages['error'] = "Error when save";
                }
            }
            else
            {
                $this->_redirect('/front/login/logout');
            }
        }
        else
        {
            $ediForm->populate(array(
                'id' => $this->userInfo->getId(),
                'username' => $this->userInfo->getUsername(),
                'name' => $this->userInfo->getName(),
                'mobile' => $this->userInfo->getMobilephone(),
                'email' => $this->userInfo->getEmail(),
                'department' => $this->userInfo->getDepartment()->getId()
            ));
        }
//        var_dump($messages); die;
        $this->view->messages = $messages;
        $this->view->userInfo = $this->userInfo;
        $this->view->editForm = $ediForm;

    }
}